#include "../tools.h"

// n 数组长度
// i 堆顶元素索引
void heapify(int arr[], int n, int i){
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if(left <= n && arr[largest] < arr[left]) largest = left;
    if(right <= n && arr[largest] < arr[right]) largest = right;

    if(largest != i){
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);
    }
}

void heapsort(int arr[], int n){
    // 建堆 - 改变 i
    for(int i = n - 1; i >= 0; --i){
        heapify(arr, n - 1, i);
    }
    
    // 调整 - 改变 n
    for(int i = n - 1; i >= 1; --i){
        swap(arr[0], arr[i]);
        heapify(arr, i - 1, 0);
    }
}

int main(int argc, char const *argv[])
{
    int arr[20] = {6, 2, 1, 7, 9, 3, 4, 5, 10, 8};

    heapsort(arr, 10);

    return 0;
}
